package com.server.questionbank.snframe.service.OllamaService.TestQuestion;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.server.questionbank.snframe.domain.QuestionBank.Question;
import com.server.questionbank.snframe.service.OllamaService.KnowledgeBaseService.TextEmbeddingService.TextEmbeddingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class TestQuestionServiceImpl implements TestQuestionService {

    @Autowired // 注入向量模型服务
    private TextEmbeddingService textEmbeddingService;

    @Override
    public float getScore(Question question, String userAnswer) throws Exception {
        // 判断题目类型
        switch (question.getQuestionType()) {
            case "判断题":
            case "选择题":
                return getSingleScore(question, userAnswer);
            case "填空题":
                return getFillScore(question, userAnswer);
            case "简答题":
            case "计算题":
                return getCalculateScore(question, userAnswer);
        }
        return 0;
    }

    // 判断题、判断题 答案传入：["a","b"]
    private float getSingleScore(Question question, String userAnswer) throws JsonProcessingException {
        // 获取题目答案
        String answer = question.getAnswer();
        // 解析题目答案 Json
        ObjectMapper mapper = new ObjectMapper();
        String[] answers = mapper.readValue(answer, String[].class);
        if (answers == null || answers.length == 0) return 0;
        String[] userAnswers = mapper.readValue(userAnswer, String[].class);
        if (userAnswers == null || userAnswers.length == 0) return 0;
        // 计算准确率
        float accuracy = 0;
        for (int i = 0; i < answers.length; i++)
        {
            if (i >= userAnswer.length()) break;
            if (userAnswers[i] == null) continue;
            // 忽略大小写比较答案是否匹配
            if (answers[i].equalsIgnoreCase(userAnswers[i])) {
                accuracy += 1;
            }
        }
        return accuracy / answers.length;
    }

    // 填空题
    private float getFillScore(Question question, String userAnswer) throws JsonProcessingException {
        // 获取题目答案
        String answer = question.getAnswer();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(answer);
        // 获取布尔值字段
        boolean disorder = rootNode.get("disorder").asBoolean();
        // 获取数组字段
        JsonNode answerNode = rootNode.get("answer");
        String[] answers = mapper.treeToValue(answerNode, String[].class);
        // 获取用户答案
        String[] userAnswers = mapper.readValue(userAnswer, String[].class);
        // 计算准确率
        float accuracy = 0;
        // 答案是否可以乱序
        if (disorder) {
            Arrays.sort(answers);
            Arrays.sort(userAnswers);
        }
        for (int i = 0; i < answers.length; i++)
        {
            if (i >= userAnswer.length()) break;
            if (userAnswers[i] == null) continue;
            // 忽略大小写比较答案是否匹配
            if (answers[i].equalsIgnoreCase(userAnswers[i])) {
                accuracy += 1;
            }
        }
        // 计算准确率
        return accuracy / answers.length;
    }

    // 计算题、简答题
    private float getCalculateScore(Question question, String userAnswer) throws Exception {
        // 获取题目答案
        String questionAnswer = question.getAnswer();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(questionAnswer);
        // 获取布尔值字段
        boolean enableKeywordCheck = false;
        try {
            enableKeywordCheck = rootNode.get("keyword").asBoolean();
        } catch (Exception e) { enableKeywordCheck = false; }
        // 获取数组字段
        JsonNode answerNode = rootNode.get("answer");
        String answer = mapper.treeToValue(answerNode, String.class);

        // 答案向量化
        float[] answerVec = textEmbeddingService.generateEmbedding(answer).block();
        float[] userAnswerVec = textEmbeddingService.generateEmbedding(userAnswer).block();

        // 计算准确率
        float vectorAccuracy = textEmbeddingService.cosineSimilarity(answerVec, userAnswerVec);

        // 如果向量相似度足够高，直接返回
        if (vectorAccuracy >= 0.7f) return vectorAccuracy;

        // 如果启用关键字匹配，计算关键字匹配的准确率
        if (enableKeywordCheck) {
            float keywordScore = textEmbeddingService.calculateKeywordScore(answer, userAnswer);

            // 结合两种评分（可调整权重）
            if (vectorAccuracy >= 0.4f) {
                // 中等相似度范围，组合评分
                return 0.7f * vectorAccuracy + 0.3f * keywordScore;
            } else {
                // 低相似度，主要依赖关键字
                return keywordScore > 0.6f ? Math.max(vectorAccuracy, 0.3f) : 0f;
            }
        }

        // 不启用关键字匹配的情况
        return vectorAccuracy > 0.6f ? vectorAccuracy : 0f;
    }

}
